<template>
  <scroll-view
    class="detailForm-wrap"
    :show-scrollbar="false"
    :scroll-x="true"
    :scroll-y="true"
  >
    <tm-table
      :table-data="tableList"
      :width="tableWidth"
      :cell-width="cellWidth"
      :stripe="stripe"
      :showHeader="showFixed"
      :headerHeight="80"
    ></tm-table>
  </scroll-view>
</template>
<script lang="ts" setup>
import { CustomFormType } from '../../workTypes'
import { computed, ref, onMounted } from 'vue'
import { model } from '@/ts/base'
import WorkCtrl from '../../common'
import * as dayjs from '../../../../tmui/tool/dayjs/esm/index'
const DayJs = dayjs.default
const showFixed = ref(true)
const stripe = ref(false)
type IProps = {
  formInfo: CustomFormType
}
const props = defineProps<IProps>()

const tableData = ref<any[]>([])
const header = ref<any[]>([])
const columns = ref<any[]>([])
onMounted(async () => {
  if (props.formInfo) {
    const detailDatas = props.formInfo?.data[0]?.after || []
    const fields = (props.formInfo?.fields || []).filter(
      field => field.options?.hideField !== true
    )

    const promises = detailDatas.map(async (detailData: any) => {
      for (const key in detailData) {
        if (Object.prototype.hasOwnProperty.call(detailData, key)) {
          const curField = fields.find(field => field.id === key)
          if (curField) {
            detailData[key] = await getFieldText(detailData, curField)
          }
        }
      }
      return detailData
    })

    await Promise.all(promises).then(result => {
      tableData.value.push(...result)
    })

    // 更新 header 和 columns
    const headOpts = {
      opts: {
        color: '#f5f5f5'
      }
    }
    header.value = []
    columns.value = []
    header.value.push({
      field: 'name',
      name: '标题',
      ...headOpts
    })
    // header.push({
    //   field: 'id',
    //   name: '唯一标识',
    //   ...headOpts
    // })
    columns.value.push('id')
    columns.value.push('name')

    fields.forEach((item: { id: any; name: any }) => {
      const jsons = {
        field: item.id,
        name: item.name,
        ...headOpts
      }
      header.value.push(jsons)
      columns.value.push(item.id)
    })
  }
})
const tableList = computed(() => {
  return {
    fields: { columns: columns.value },
    header: header.value,
    data: tableData.value
  }
})
const getFullPath = (lookups: model.XLookup[], targetValue: string): string => {
  const valueNode = lookups.find(item => item.value === targetValue)
  if (!valueNode) return ''

  const path: string[] = [valueNode.text]
  let currentNode = valueNode
  
  while (currentNode.parentId) {
    const parentNode = lookups.find(item => item.id === currentNode.parentId)
    if (!parentNode) break
    path.unshift(parentNode.text)
    currentNode = parentNode
  }
  
  return path.join('/')
}
const getFieldText = async(_data: any, _fields: model.FieldModel) => {
  const _value = _data[_fields.id]
  switch (_fields.valueType) {
    case '日期型':
      return DayJs(_value).format('YYYY-MM-DD HH:mm:ss')
    case '时间型':
      return DayJs(_value).format(' HH:mm:ss')
    case '数值型':
      return _value ?? '-'
    case '选择型':
      return _fields.lookups!.find(v => v.value === _value)?.text
    case '分类型': 
      return getFullPath(_fields.lookups!, _value) 
    case '用户型':
      return (await loadUserInfo(_value))?.name
    case '附件型':
    case '引用型': {
      if (!_value) return '-'
      try {
        const parsed = Array.isArray(_value) ? _value : JSON.parse(_value)
        return Array.isArray(parsed) ? parsed.map((d: any) => d.name) : '-'
      } catch (e) {
        return '-'
      }
    }
    default:
      return _value ?? '-'
  }
}
// 计算table宽度
const cellWidth = ref<number>(160)
const tableWidth = computed(() => {
  return uni.$tm.u.torpx(tableList.value.header.length * cellWidth.value)
})
/** 加载用户型信息 */
const loadUserInfo = async (id: string) => {
  try {
    const user = await WorkCtrl.findWorkEntityAsync(id)
    if (user) {
      return user
    }
  } catch (error) {
    return null
  }
}
</script>

<style lang="scss">
.detailForm-wrap {
}
</style>
